package sort;

public class MergeSort {

    private static int[] aux;

    public static void sort(int[] array) {
        int N = array.length;
        aux = new int[N];
        sort(array,0, array.length-1);

    }

    private static void sort(int[] array, int lo, int hi) {
        if (hi<=lo){return;}
        int mid = (lo + hi) /2;
        sort(array,lo,mid);
        sort(array,mid+1,hi);
        merge(array, lo,mid,hi);
    }

    private static void merge(int[] a, int lo, int mid, int hi) {
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; k++) {
            aux[k] = a[k];
        }
        for (int k = lo; k <= hi; k++) {
            if (i > mid) {
                a[k] = aux[j++];
            } else if (j > hi) {
                a[k] = aux[i++];
            }
            else if (aux[j]<aux[i]){
                a[k] = aux[j++];
            }
            else {
                a[k] = aux[i++];
            }
        }
    }
}
